
package poplar.dc.user;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.*;
import java.io.*;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;

@Stateless
@Remote(UserRemote.class)
public class UserBean implements UserRemote{
	String resource_ = "mybatis.xml";	
	SqlSessionFactory sqlMapper_ = null;
	
	@Override
	public int insertUser( User user ){
		int result = 0;
		SqlSession session = sqlMapper_.openSession();
		
		try{
			result = session.insert( "UserMapper.insert_user", user );			
		} 
		catch( Exception e ){
			System.out.println( e.getMessage() );
			return result;
		}
		finally{
			session.commit();
			session.close();
		}
		
		return result;
	}
	
	@Override
	public User getUser( String strid ){
		User user = null;
		SqlSession session = sqlMapper_.openSession();
		
		try{
			user = ( User )session.selectOne( "UserMapper.select_user", strid );			
		} 
		catch( Exception e ){
			System.out.println( e.getMessage() );
		}
		finally{
			session.close();
		}
		
		return user;
	}
	
	@Override	
	public long getUid( String id ){
		long uid = 0;		
		SqlSession session = sqlMapper_.openSession();
		
		try{
			Object o = session.selectOne( "UserMapper.select_uid", id );
			uid = Long.parseLong( o.toString() );
		} 
		catch( Exception e ){
			System.out.println( e.getMessage() );
		}
		finally{
			session.close();
		}
		
		return uid;
	}	
	
	@PostConstruct
	public void initialize(){	
		try{
			Reader reader = Resources.getResourceAsReader( resource_ );
			sqlMapper_ = new SqlSessionFactoryBuilder().build( reader );			
		} 
		catch( IOException e ){
			e.printStackTrace();
		}
	}	
	
	@PreDestroy
	public void destroyBean(){
		sqlMapper_ = null;
	}
}
